
const app = getApp()
const util = require('../../utils/util.js')

Page({
  data: {
    statusType:[
      {
        status: 9999,
        label: '全部'
      },
      {
        status: 0,
        label: '待付款'
      },
      {
        status: 1,
        label: '待收货'
      },
      {
        status: 2,
        label: '待评价'
      },
      {
        status: 3,
        label: '已完成'
      },
    ],// ["待付款","待收货", "待评价","已完成", "全部订单"],
    badges: [0, 0, 0, 0, 0],
    hasRefund: false,
    status: 9999,
    tabClass: ["",  "", "", "", ""]
  },
  statusTap: function (e) {
    const curType = e.currentTarget.dataset.status;
    this.data.status = curType
    this.setData({
      status: curType
    });
    this.onShow();
  },
  onLoad: function (options) {
    
   
    if (options && options.type) {
      //退款
      if (options.type == 99) {
        this.setData({
          hasRefund: true,
          status: parseInt(options.type)
        });
      } else {
        this.setData({
          hasRefund: false,
          status:parseInt(options.type)
        });
      }
    }
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

  },
  querenshouhuo(e){
    const that = this;
    const orderId = e.currentTarget.dataset.id;
  
    wx.showModal({
      title: '确定已完成配送吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
        
          db.collection('orders').doc(orderId).update({
            data: {
              delivered: 2,
              status:2,
              logisticsStatus:1
            },
            success: function(res) {
              console.log(res)
              that.doneShow();

            }
          })
         
          
        }
      }
    })
  },
  cancelOrderTap: function (e) {
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    const couponidId = e.currentTarget.dataset.couponid
    const upgoodsStatores = e.currentTarget.dataset.goods
    
    wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
        
          db.collection('orders').doc(orderId).remove({
            
            success: function(res) {
              console.log(res)
              
            }
          })
          //库存加回来 已售数量减去
          const _ = db.command
          for (let index = 0; index < upgoodsStatores.length; index++) {
            const goods_ = upgoodsStatores[index];
            db.collection('goods').doc(goods_.goodsId).update({
              data: {
                stores: _.inc(goods_.number),
                numberOrders: _.inc(-goods_.number),
              },
              success: function(res) {
                
              }
            })
          }
          
          if(couponidId){
            db.collection('coupons').doc(couponidId).update({
              data: {
                status:0
              },
              success: function(res) {
                
              }
            })
          }
          that.onShow();
        }
      }
    })
  },
   refundApply (e) {
     // 申请售后
     const orderId = e.currentTarget.dataset.id;
     const amount = e.currentTarget.dataset.amount;
     wx.navigateTo({
       url: "/pages/refundApplay/refundApply?id=" + orderId + "&amount=" + amount
     })
   },
  toPayTap: function (e) {
    // 防止连续点击--开始
    if (this.data.payButtonClicked) {
      wx.showToast({
        title: '休息一下~',
        icon: 'none'
      })
      return
    }
    this.data.payButtonClicked = true
    setTimeout(() => {
      this.data.payButtonClicked = false
    }, 3000) // 可自行修改时间间隔（目前是3秒内只能点击一次支付按钮）
    // 防止连续点击--结束
    const that = this;
    //订单编号去支付
    const ordernumber = e.currentTarget.dataset.ordernumber;
     console.log(ordernumber)
    ///金额
    
    let money = e.currentTarget.dataset.money;
    const needScore = e.currentTarget.dataset.score;
    //WXAPI.userAmount(wx.getStorageSync('token')).then(function (res) {
     
        // 增加提示框
        /**
         * if (res.data.score < needScore) {
          wx.showToast({
            title: '您的积分不足，无法支付',
            icon: 'none'
          })
          return;
        }
         
        let _msg = '订单金额: ' + money + ' 元'
        if (res.data.balance > 0) {
          _msg += ',可用余额为 ' + res.data.balance + ' 元'
          if (money - res.data.balance > 0) {
            _msg += ',仍需微信支付 ' + (money - res.data.balance) + ' 元'
          }
        }
        if (needScore > 0) {
          _msg += ',并扣除 ' + money + ' 积分'
        }
        money = money - res.data.balance
        */
        wx.showModal({
          title: '请确认支付',
          content:  '订单金额: ' + money + ' 元',
          confirmText: "确认支付",
          cancelText: "取消支付",
          success: function (res) {
            console.log(res);
            if (res.confirm) {
             // that._toPayTap(orderId, money)
              wx.cloud.callFunction({
                name: "payFun",
                data: {
                  body: "蘑菇云-超市",
                  orderid: ordernumber,
                  money:money,
                  nonceStr:""
                },
                success(res) {
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  console.log("提交成功", res.result)
                  //创建订单操作，在自定义的保存订单的成功回调中使用下面的函数
                  //this.pay(res.result, res._id)
                  const payment = res.result.payment
                  wx.requestPayment({
                    ...payment, //。。。是展开变量的语法 
                    success(res) {
                      console.log("pay success", res)
                      //跳转到支付成功页面
                      that.onLoad()
                    },
                    fail(res) {
                      console.error("pay fail", res)
                      //跳转到支付失败页面
                      that.onLoad()
                      wx.showModal({
                        title: '错误',
                        content: '没支付功能',
                        showCancel: false
                      })
                    }
                  })
                },
                fail(res) {
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  console.log("提交失败", res)
                }
              })
            } else {
              console.log('用户点击取消支付')
            }
          }
        });
     
    //})
  },
 
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  getOrderStatistics: function () {
    var that = this;
    if(wx.getStorageSync('token')) {
     // if (res.code == 0) {
        var tabClass = that.data.tabClass;
        if (res.data.count_id_no_pay > 0) {
          tabClass[0] = "red-dot"
        } else {
          tabClass[0] = ""
        }
        if (res.data.count_id_no_transfer > 0) {
          tabClass[1] = "red-dot"
        } else {
          tabClass[1] = ""
        }
        if (res.data.count_id_no_confirm > 0) {
          tabClass[2] = "red-dot"
        } else {
          tabClass[2] = ""
        }
        if (res.data.count_id_no_reputation > 0) {
          tabClass[3] = "red-dot"
        } else {
          tabClass[3] = ""
        }
        if (res.data.count_id_success > 0) {
          //tabClass[4] = "red-dot"
        } else {
          //tabClass[4] = ""
        }

        that.setData({
          tabClass: tabClass,
        });
   //   }
    }
  },
  onShow: function () {
   // AUTH.checkHasLogined().then(isLogined => {
     var isLogined = true
      if (isLogined) {
        this.doneShow();
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/user/index"
              })
            } else {
              wx.navigateBack()
            }
          }
        })
      }
 //   })
  },
  doneShow: function () {
    
    // 获取订单列表
    var that = this;
    var where ={}
    if ( that.data.status == 9999) {
    
      where = {
        _openid:wx.getStorageSync('openid')
     }
    }else{
      where = {
        status:that.data.status,  
        _openid:wx.getStorageSync('openid')
     }
     
    }
 
    wx.cloud.callFunction({
      // 云函数名称
      name: 'crud',
      // 传给云函数的参数
      data: {
        db:"orders",
        type:"getall",
        data:"",
        indexKey:"",
        //待筛选的参数-库存 >0 commandtype [{ 
          //type:'gt',
         // ziduan:'stores',
       //   value:0}，{},{}]
        commandtype:[],
        condition:where,
      },
    })
    .then(res => {
   
   // this.getOrderStatistics();{"status":parseInt(that.data.status),_openid:wx.getStorageSync('openid')}
   // const db = wx.cloud.database()
   //  db.collection('orders').where(where).orderBy("dateAdd","desc").get({
    //    success: res => {
          console.log( res )
          if (res.result && res.result.data  && res.result.data.length > 0) {
            for (let index = 0; index <res.result.data.length; index++) {
              //  const oeder = res.data[index];
              //oeder['statusStr']=statusType[order.status]
            }
            that.setData({
              orderList: res.result.data,
              // logisticsMap: res.data.logisticsMap,
              //goodsMap: res.data.goodsMap
            });

          } else {
              that.setData({
              orderList: null,
             // logisticsMap: {},
            //  goodsMap: {}
            });
            }
          })
      // }
      //})
  //  })
  },
})